# ========= 引入基础的模块 ========
from resources_base.module_base.importmodules import *

# ========= 导入数据 =============
from userweb.models import *
# ========= 导入DRF模块 ====================
from rest_framework.views import APIView
from userweb.serializer import *
from rest_framework.viewsets import ModelViewSet
# 导入认证类
from rest_framework.authentication import BasicAuthentication, SessionAuthentication, TokenAuthentication
# 导入权限类
from rest_framework.permissions import IsAuthenticated




# ============== 基于系统默认的user
""""
from rest_framework.authtoken.models import Token
class MyAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_TOKEN', None)
        if not token:
            raise exceptions.AuthenticationFailed('请提交token')  # exceptions 会被自定义的错误处理捕捉，并返回
        try:
            obj_token = Token.objects.get(key = token)
            print(obj_token)
            user = User.objects.get(pk=obj_token.user_id)
            return (user, None)   #返回的数据由 request.user 接收
        except Exception as e:
            raise exceptions.AuthenticationFailed('验证失败')


class LoginView(APIView):

    def get(self, request, *args, **kwargs):
        # 返回页面
        return render(request, 'user/login.html')

    def post(self, request, *args, **kwargs):
        # 获取用户名和密码
        user_obj = User.objects.filter(username = request.POST.get('loginid', None)).first()

        # 判断
        if not user_obj:
            return JsonResponse({'code': 0, 'error': '该用户不存在！'})

        login_info = {
            'username': user_obj.username,
            'password': request.POST.get('loginpwd', None)
        }
        # 验证
        user = authenticate(**login_info)
        # 判断
        if not user:
            return JsonResponse({'code': 0, 'error': '账号和密码错误！'})

        token = get_md5(user_obj.username)

        # 写入token
        Token.objects.update_or_create(user=user_obj, defaults={'key': token})

        # 返回
        return JsonResponse({'code': 1, 'token':token })
"""


# ============== 自定义的====
"""

class MyAuthentication(BaseAuthentication):

    def authenticate(self, request):
        token = request.META.get('HTTP_TOKEN', None)
        if not token:
            raise exceptions.AuthenticationFailed('请提交token')  # exceptions 会被自定义的错误处理捕捉，并返回
        try:
            obj_token = AToken.objects.get(token = token)
            print(obj_token)
            user = Account.objects.get(pk=obj_token.account_id)
            return (user, token)   #返回的数据由 request.user 接收
        except Exception as e:
            raise exceptions.AuthenticationFailed('无法验证token信息')


class LoginView(APIView):

    def get(self, request, *args, **kwargs):
        # 返回页面
        return render(request, 'user/login.html')


    def post(self, request, *args, **kwargs):
        # 获取用户名和密码
        user_obj = Account.objects.filter(loginid = request.POST.get('loginid', None))

        # 判断
        if not user_obj:
            return JsonResponse({'code': 0, 'error': '该用户不存在！'})

        # ======== 判断 ======
        user_obj = user_obj.filter(loginpwd = request.POST.get('loginpwd'))
        # 判断
        if not user_obj:
            return JsonResponse({'code': 0, 'error': '账号和密码错误！'})

        # 获取当前用户对象
        current_user = user_obj[0]
        # 获取token
        token = get_md5(current_user.name)

        # 写入token
        AToken.objects.update_or_create(account=current_user, defaults={'token': token})

        # 返回
        return JsonResponse({'code': 1, 'token':token })
        
"""


class LoginView(APIView):

    def get(self, request, *args, **kwargs):
        # 返回页面
        return render(request, 'user/login.html')


    def post(self, request, *args, **kwargs):
        pass



"""
def index(request):
    # 登录页面 
    return render(request, 'user/login.html')
"""

from rest_framework.permissions import BasePermission

class MyPermission(BasePermission):
    message = "sorry,您没有权限"
    def has_permission(self, request, view):
        # 内置封装的方法
        '''
        判断该用户有没有权限
        '''
        # 判断用户是不是VIP用户
        # 如果是VIP用户就返回True
        # 如果是普通用户就返会Flase

        if request.method in ["POST","PUT","DELETE", 'GET']:
            # print(111)
            print(request.user.username)
            print(request.user.type)
            print(type(request.user.type))
            if request.user.type == 2:   # 是VIP用户
                print(2222)
                return True
            else:
                return False
        else:
            return True


from rest_framework_jwt.authentication import JSONWebTokenAuthentication


class AccounViewSet(ModelViewSet):
    queryset = Account.objects.all()
    serializer_class = AccountSerializer

    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]


class RolesViewSet(ModelViewSet):
    queryset = Roles.objects.all()
    serializer_class = Roleserializer

    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]


class DepartmentViewSet(ModelViewSet):
    queryset = Department.objects.all()
    serializer_class = DepartmentSerializer


class PositionViewSet(ModelViewSet):
    queryset = Position.objects.all()
    serializer_class = PositionSerializer

